package leetcodecompetition.D347;

import java.util.HashSet;
import java.util.Set;

/**
 * @Author: Siantar
 * @Date: 2023-05-28-10:46
 * @Description: 1.0
 */
public class T6440 {
    public int[][] differenceOfDistinctValues(int[][] grid) {
        int m = grid.length;
        int n = grid[0].length;
        int[][] topLeft = new int[m][n];
        int[][] bottomRight = new int[m][n];
        int[][] answer = new int[m][n];
        for (int a = 0; a < n; a++) {
            int i = 0;
            int j = a;
            Set<Integer> set = new HashSet<>();
            while (i < m && j < n) {
                topLeft[i][j] = set.size();
                set.add(grid[i][j]);
                j++;
                i++;
            }
            i = m - 1;
            j = a;
            set.clear();
            while (i >= 0 && j >= 0) {
                bottomRight[i][j] = set.size();
                set.add(grid[i][j]);
                j--;
                i--;
            }
        }
        for (int a = 0; a < m; a++) {
            int i = a;
            int j = 0;
            Set<Integer> set = new HashSet<>();
            while (i < m && j < n) {
                topLeft[i][j] = set.size();
                set.add(grid[i][j]);
                j++;
                i++;
            }
            i = a;
            j = n - 1;
            set.clear();
            while (i >= 0 && j >= 0) {
                bottomRight[i][j] = set.size();
                set.add(grid[i][j]);
                j--;
                i--;
            }
        }
        for (int i = 0; i < m; i++) {
            for (int j = 0; j < n; j++) {
                answer[i][j] = Math.abs(topLeft[i][j] - bottomRight[i][j]);
            }
        }
        return answer;
    }
}
